package com.senlingspace.system.service.impl;

import com.senlingspace.common.enums.OrderBusinessStatus;
import com.senlingspace.common.enums.TeamStatus;
import com.senlingspace.system.domain.*;
import com.senlingspace.system.domain.dto.DeviceVisitDto;
import com.senlingspace.system.mapper.*;
import com.senlingspace.system.service.SlkjOrderTourDoneService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 用户游览完成后接口调用，修改订单状态
 * 
 * @author
 * @date 2024-07-15
 */
@Slf4j
@Service
public class SlkjOrderTourDoneServiceImpl implements SlkjOrderTourDoneService
{
    @Autowired
    private SlkjOperateMapper slkjOperateMapper;

    @Autowired
    private SlkjOrderTrackingMapper slkjOrderTrackingMapper;

    @Autowired
    private SlkjOrderMapper slkjOrderMapper;

    @Autowired
    private SlkTeamStatusMapper slkTeamStatusMapper;

    @Autowired
    private SlkjTeamEqumentMapper slkjTeamEqumentMapper;

    @Autowired
    private SlkjPlayRequestLogMapper slkjPlayRequestLogMapper;

    @Autowired
    private HttpServletRequest httpServletRequest;


    @Override
    @Transactional
    public void updateOrderBusinessStatus(DeviceVisitDto deviceVisitDto) {
        // *1.存储调用日志 如果日志中存在则不在走任何逻辑，直接返回成功。 同一设备 and 同一订单号只能存在一条数据。如果多次请求，只存最早的一条数据

        long startTime = System.currentTimeMillis();
        SlkjPlayRequestLog logEntry = new SlkjPlayRequestLog();
        try {
            // 设置日志基本信息
            logEntry.setMethod("updateOrderBusinessStatus");
            logEntry.setRequestMethod(httpServletRequest.getMethod());
            logEntry.setOperUrl(httpServletRequest.getRequestURI());
            logEntry.setOperIp(httpServletRequest.getRemoteAddr());
            logEntry.setOperParam(deviceVisitDto.toString());
            logEntry.setOperTime(new Date());


            log.info("浏览完成 修改指定订单，组队信息状态"+deviceVisitDto.toString());

    //        订单状态的处理，改为已完成   这里需要判断订单中的票张数  和实际 返回的使用的票张数 （使用张数需要自己去查询）
            String orderNumber = deviceVisitDto.getOrderNumber();
            List<SlkjOrderTracking> slkjOrderTrackings = slkjOrderTrackingMapper.selectByOrderNumbers(orderNumber);

            if (!CollectionUtils.isEmpty(slkjOrderTrackings) && slkjOrderTrackings.size() > 0) {
                SlkjOrderTracking slkjOrderTracking = slkjOrderTrackings.get(0);
                Integer validatedTicketQuantity = slkjOrderTracking.getValidatedTicketQuantity();
                Integer includedTicketQuantity = slkjOrderTracking.getIncludedTicketQuantity();
                if (validatedTicketQuantity == includedTicketQuantity ) {

                    SlkjOrder slkjOrder = new SlkjOrder();
                    slkjOrder.setOrderNumber(orderNumber);
                    slkjOrder.setBusinessStatus(OrderBusinessStatus.COMPLETED.getCode());
                    slkjOrderMapper.updateSlkjOrderByOrderNumber(slkjOrder);

                }else{
                    log.info("指定订单的票数为完全使用，无法修改状态为已完成，orderNumber：： ", orderNumber);
                }
            }else{
                log.error("未查询到指定订单的信息,修改失败，orderNumber：： ", orderNumber);
            }


    //        修改队伍的状态信息  slkj_team_status 改为 SUCCESS 已完成
            SlkTeamStatus slkTeamStatus = new SlkTeamStatus();
            slkTeamStatus.setTeamId(deviceVisitDto.getGroupId());
            slkTeamStatus.setTeamStatus(TeamStatus.SUCCESS.getCode());
            slkTeamStatusMapper.updateSlkTeamStatus(slkTeamStatus);


    //        修改 门店队伍设备信息的状态   slkj_team_equment 改为 SUCCESS 已完成
            SlkjTeamEqument slkjTeamEqument = new SlkjTeamEqument();
            slkjTeamEqument.setOrderNumber(orderNumber);
            slkjTeamEqument.setUuid(deviceVisitDto.getUuid());
            slkjTeamEqument.setTeamId(deviceVisitDto.getGroupId());
            slkjTeamEqument.setTeamId(deviceVisitDto.getGroupId());
            slkjTeamEqument.setStatus(TeamStatus.SUCCESS.getCode());
            slkjTeamEqumentMapper.updateStatus(slkjTeamEqument);

            // 事务操作成功，记录日志
            logEntry.setStatus(0L); // 0 表示正常


        } catch (RuntimeException e) {
            log.error("订单处理失败，订单号：" + deviceVisitDto.getOrderNumber(), e);

            // 记录异常信息到日志表
            logEntry.setStatus(1L); // 1 表示异常
            logEntry.setErrorMsg(e.getMessage());
            throw e; // 继续抛出异常，确保事务回滚
        } finally {
            SlkjPlayRequestLog slkjPlayRequestLog = new SlkjPlayRequestLog();
            String param = "uuid='" + deviceVisitDto.getUuid() + '\'' + ", groupId=" + deviceVisitDto.getGroupId();
            slkjPlayRequestLog.setOperParam(param);
            slkjPlayRequestLog.setStatus(0L);
            List<SlkjPlayRequestLog> slkjPlayRequestLogs = slkjPlayRequestLogMapper.selectLogList(logEntry);
            if (CollectionUtils.isEmpty(slkjPlayRequestLogs)) {
                // 记录消耗时间
                long costTime = System.currentTimeMillis() - startTime;
                logEntry.setCostTime(costTime);
                // 插入日志记录到数据库
                slkjPlayRequestLogMapper.insertSlkjPlayRequestLog(logEntry);
            }
        }

    }
}
